<?php

namespace app\controller\admin;

use app\core\ApiController;
use app\service\BlessingOrderService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class BlessingOrder extends ApiController
{
    /**
     *订单列表
     */
    public function list()
    {
        $page = input('post.page', 1);
        $limit = input('post.limit', 10);
        $searchQuery = input('post.', []);
        $list = BlessingOrderService::invoke()->list($page, $limit, $searchQuery);
        $num = \app\model\BlessingOrder::where(['status' => 2])->count();
        $money = \app\model\BlessingOrder::where(['status' => 2])->sum('price');
        $list['num'] = $num;
        $list['money'] = $money;
        $this->response->success($list);
    }

    /**
     *订单详情接口
     */
    public function info()
    {
        $order_id = input('get.order_id');
        $data = BlessingOrderService::invoke()->info($order_id);
        $this->response->success($data);
    }

    public function export()
    {
        $searchQuery = input('post.', null);
        $searchQuery['order_type'] = 1;
        //1.从数据库中取出数据
        $list = BlessingOrderService::invoke()->getExportList($searchQuery);
        $list = array_values($list);
        foreach ($list[0] as $value) {
            $data[] =
                [
                    'order_no' => $value['order_no'],
                    'temple_name' => $value['temple_name'],
                    'temple_id' => $value['temple_id'],
                    'lamp' => '祈福灯',
                    'type_name' => $value['type_name'],
                    'price' => $value['price'],
                    'status_name' => $value['status_name'],
                    'create_time' => $value['create_time'],
                    'pay_time' => $value['pay_time'],
                ];
        }
        $xlsName = "订单导出" . date("YmdHis", time());//文件名称
        $head = ['订单编号', '寺庙名称', '寺庙账号', '功德灯名称', '供灯方式', '金额', '订单状态', '创建时间', '支付时间'];// 表头信息
        //表字段和表头信息一一对应
        $keys = ['order_no', 'temple_name', 'temple_id', 'lamp', 'type_name', 'price', 'status_name', 'create_time', 'pay_time'];
        $this->downloadExcel($xlsName, $data ?? [], $head, $keys);
    }

    /*
     * 导出数据
     */
    public function downloadExcel($name, $data = [], $head = [], $keys = [])
    {

        $count = count($head);  //计算表头数量
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        for ($i = 65; $i < $count + 65; $i++) {     //数字转字母从65开始，循环设置表头：
            $sheet->setCellValue(strtoupper(chr($i)) . '1', $head[$i - 65]);
        }
        //循环设置单元格：
        foreach ($data as $key => $item) {
            //$key+2,因为第一行是表头，所以写到表格时   从第二行开始写
            for ($i = 65; $i < $count + 65; $i++) {
                //数字转字母从65开始：
                $sheet->setCellValue(strtoupper(chr($i)) . ($key + 2), $item[$keys[$i - 65]]);
                //固定列宽
                $spreadsheet->getActiveSheet()->getColumnDimension(strtoupper(chr($i)))->setWidth(20);
            }
        }
        $names = $name;
        //utf-8转unicode格式
        $name = iconv('UTF-8', 'UCS-2BE', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2) {
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0) {
                $str .= '\u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
            } else {
                $str .= '\u' . str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
            }
        }
        ob_end_clean();
        header("Content-Type:application/vnd.ms-excel");
        header("Cache-Control:max-age=0");
        header('Data-Type: binary');
        header('Data-Filename: ' . $str);
        header('Content-Disposition: attachment;filename="' . $names . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Access-Control-Expose-Headers:Data-Type,Data-Filename');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

    }


}